/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dandsoft.mavrep.data;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;

/**
 *
 * @author fin
 */
public class ChecksumResource implements InputStreamResource{

    private Checksum.Type checksumType;
    private String checksum;
    
    public ChecksumResource(Checksum.Type checksumType, Resource resource) {
        this.checksumType = checksumType;

        MessageDigest digest = null;

        try {
            digest = MessageDigest.getInstance(checksumType.toString());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = null;

        try {
            in = ((InputStreamResource) resource).getInputStream();
            byte[] buffer = new byte[1024];
            int n;
            while ((n = in.read(buffer)) > 0) {
                out.write(buffer, 0, n);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                }
            }
        }
        digest.update(out.toByteArray());
        this.checksum = Hex.encodeHexString(digest.digest());
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(checksum.getBytes("UTF-8"));
    }

    @Override
    public int getSize() {
        return checksum.length();
    }


}
